package com.zlm.app;

import com.zlm.bean.ChannelPromotionCount;
import com.zlm.bean.MarketingUserBehavior;
import com.zlm.common.SimulateMarketingBehaviorSourceFunction;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * Author: Harbour
 * Date: 2021-05-17 9:03
 * Desc: 整体统计用户市场行为
 */
public class MarketStatisticApp {
    public static void main(String[] args) throws Exception {
        // step 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        // step 2 获取数据源
        DataStream<MarketingUserBehavior> inputDataStream = env.addSource(new SimulateMarketingBehaviorSourceFunction());

        // step 3 对数据源进行转换
        inputDataStream
                .filter(data -> !"UNINSTALL".equalsIgnoreCase(data.getBehavior()))
                .assignTimestampsAndWatermarks(new AscendingTimestampExtractor<MarketingUserBehavior>() {
                    @Override
                    public long extractAscendingTimestamp(MarketingUserBehavior element) {
                        return element.getTimestamp();
                    }
                })
                .map(new MapFunction<MarketingUserBehavior, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> map(MarketingUserBehavior value) throws Exception {
                        return new Tuple2<String, Long>("total", 1L);
                    }
                })
                .keyBy(0)
                .timeWindow(Time.hours(1), Time.seconds(5))
                .aggregate(new MyAggFunction(), new MyFullWindowFunction())
                .print();

        env.execute();
    }

    private static class MyFullWindowFunction implements WindowFunction<Long, ChannelPromotionCount, Tuple, TimeWindow> {

//        @Override
//        public void process(Tuple tuple, Context context, Iterable<Long> elements, Collector<ChannelPromotionCount> out) throws Exception {
//            out.collect(new ChannelPromotionCount(
//                    "total",
//                    tuple.getField(0),
//                    String.valueOf(context.window().getEnd()),
//                    elements.iterator().next())
//            );
//        }

        @Override
        public void apply(Tuple tuple, TimeWindow window, Iterable<Long> input, Collector<ChannelPromotionCount> out) throws Exception {
            out.collect(new ChannelPromotionCount(
                "total",
                tuple.getField(0),
                String.valueOf(window.getEnd()),
                input.iterator().next())
            );
        }
    }

    private static class MyAggFunction implements AggregateFunction<Tuple2<String, Long>, Long, Long> {

        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(Tuple2<String, Long> value, Long accumulator) {
            return accumulator + 1;
        }

        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return a + b;
        }
    }
}
